package com.sigmatrix.h5.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sigmatrix.h5.dao.DisRebateAuditRecordDao;
import com.sigmatrix.h5.entity.DisRebateAudit;
import com.sigmatrix.h5.entity.DisRebateAuditRecord;
import com.sigmatrix.h5.service.DisRebateAuditRecordService;
import com.sigmatrix.h5.service.DisRebateAuditService;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.web.mode.RebateTotal;
import com.sigmatrix.sc.jdbc.common.service.ServiceImpl;

/**
 * 
 *@ClassName: DisRebateAuditRecordServiceImpl
 *@Description:返利审核记录
 *@author MH
 *@date 2018年1月25日 上午11:14:41
 */
@Service
public class DisRebateAuditRecordServiceImpl extends ServiceImpl<DisRebateAuditRecord,Integer> implements DisRebateAuditRecordService{
	@Autowired
	private DisRebateAuditRecordDao disRebateAuditRecordDao;
	
	@Autowired
	private DisRebateAuditService disRebateAuditService;

	@Override
	public Integer save(DisRebateAudit audit) {
		DisRebateAuditRecord record = new DisRebateAuditRecord();
		DisRebateAuditRecord lastRecord = findLastRecord(audit.getDealerId(), audit.getDealerType(), audit.getRebateActivityId());
		if(CommonUtils.isNotEmpty(lastRecord)){
			record.setNoAuditAmount(lastRecord.getNoAuditAmount());
			record.setCount(lastRecord.getCount()+1);
			record.setSum(lastRecord.getSum().add(audit.getAmount()));
		}else{
			RebateTotal total = disRebateAuditService.statisticByDealerAndActivity(audit.getDealerId(), audit.getDealerType(), audit.getRebateActivityId());
			record.setNoAuditAmount(total.getSum().subtract(audit.getAmount()));
			record.setCount(total.getCount());
			record.setSum(total.getSum());
		}
		record.setAuditAmount(audit.getAmount());
		record.setAuditReason("自动审核通过");
		record.setDealerId(audit.getDealerId());
		record.setDealerType(audit.getDealerType());
		record.setRebateActivityId(audit.getRebateActivityId());
		record.setCreateTime(new Date());
		return insertSelective(record);
	}
	
	private DisRebateAuditRecord findLastRecord(Integer dealerId,Short dealerType,Integer activityId){
		DisRebateAuditRecord record = new DisRebateAuditRecord();
		record.setDealerId(dealerId);
		record.setDealerType(dealerType);
		record.setRebateActivityId(activityId);
		Map<String,String> order = new HashMap<String,String>();
		order.put("createTime", "desc");
		order.put("id", "desc");
		return disRebateAuditRecordDao.selectOne(record, order);
	}

}
